import Vue from 'vue'
import Vuex from 'vuex'
import rq from '../../requests'
import router from '../../router'
import qs from 'qs'
import { Notify } from 'vant';
Vue.use(Vuex)

export default {
  namespaced: true,
      //令牌header 令牌body 哈希值
      state: {
        // userToken: 'xu456as:1632282086180:nbwk0yo/4ahDjzkxb4td36oilFk=',
        userToken: "",
        inputUsername: '',
        inputPassword: '',
        profile: {id: null, username: null, nickName: null, avatarHash: null},
        avatarUrl: null
      },
      mutations: {
        clear(state) {
          state.userToken = '';
          state.inputUsername = '';
          state.password = '';
          state.profile = {};
        },
        memoryInput(state, {username, password}) {
          state.inputUsername = username
          state.inputPassword = password
        },
        setToken(state, {token}) {
          state.userToken = token;
        },
        setProfile(state, {profile}) {
          state.profile = profile;
        },
        setAvatarUrl(state, {avatarUrl}) {
          state.avatarUrl = avatarUrl
        },
      },
      getters: {
        // getters 或 computed 都是 只读的
        // 就是显示界面中
        // 计算 登录的状态
        isLogin:
            (state) => {
              return !!state.userToken  // 转换位布尔值，逻辑取反运算 再取反
            },
        getProfile: (state) => {
          return state.profile;
        },
        getAvatarUrl: (state) => {
          return state.avatarUrl
        },
      },
      actions: {
        getProfile({commit,dispatch}, {userToken}) {
          let body = {userToken: userToken};
          let bodyStr = qs.stringify(body);
          rq.requests.post('/fic/user/profile/get', bodyStr)
              .then(({eCode, res, eMessage}) => {
                if (!eCode) {
                  let profile = res;
                  if (profile) {
                    commit("setProfile", {profile: profile})
                    Notify({ type: 'info', message: "登录成功"});
                    dispatch("downloadAvatar");
                    return;
                  }
                }
                Notify({ type: 'danger', message: eMessage });
              })
              .catch(error => console.log(error));
        },
        register(
            {commit, dispatch, rootState}, {username, password, nickName, avatarFile}) {
          let formData = new FormData();
          let groupToken = rootState.group.selectedGroupToken || "";
          formData.append('username', username);
          formData.append('nickName', nickName);
          formData.append('password', password);
          formData.append("avatar", avatarFile.file);

          let config = {headers: {'Content-Type': 'multipart/form-data'}};
          rq.requests.post("/fic/user/register", formData, config)
              .then(({eCode, res, eMessage}) => {
                if (!eCode) {
                  let token = res.userToken;
                  if (token) {
                    commit("setToken", {token: token})
                    Notify({ type: 'info', message: "注册成功"});
                    dispatch("getProfile", {userToken: token});
                    router.push({path: '/record'});
                    return;
                  }
                  Notify({ type: 'danger', message: eMessage });
                  router.push({path: '/login'});
                }
              })
              .catch(error => console.log(error));

          //   let body = {username, password, nickName}
          //   let bodyStr = qs.stringify(body)

          //   rq.requests.post('/fic/user/register', bodyStr)
          //   .then(({eCode, res, eMessage}) => {
          //     if(!eCode) {
          //       let token = res.userToken;
          //       if(token) {
          //         commit("setToken", {token: token})
          //         Notify({ type: 'info', message: "注册成功"});
          //         dispatch("getProfile", {
          //           userToken: token
          //         });
          //         router.push({path: '/record'});
          //         return
          //       }
          //     }
          //     Notify({ type: 'danger', message: eMessage });
          //     router.push({path: '/login'});
          //   })
          //   .catch(error => console.log(error))
        },
        login({commit, dispatch}, {username, password}) {
          let body = {username, password} 
          commit("memoryInput", body);
          let bodyStr = qs.stringify(body)
          rq.requests.post('/fic/user/login/', bodyStr)
              .then(({eCode, res, eMessage}) => {
                if (!eCode) {
                  let token = res.userToken;
                  console.log("receive userToken: " + token);
                  if (token) {
                    commit("setToken", {token: token})
                    Notify({ type: 'info', message: "登录成功"});
                    dispatch("getProfile", {userToken: token});
                    router.push({path: '/record'});
                    return
                  } else {
                    commit("setToken", {})
                    Notify({ type: 'warn', message: "账号或密码不正确"});
                    return;
                  }
                }
                router.push({path: '/register'});
              })
              .catch(error => console.log(error))
        },
        downloadAvatar({commit, state, rootState, dispatch}) {
          console.log('Enter downloadAvatar')
          let fileHash = state.profile.avatarHash
          console.log('fileHash: ' + fileHash)
          if (!fileHash) {
            return;
          }
          let body = {'fileHash': fileHash};
          rq.requests
              .post(
                  '/fic/pic/avatar/download', qs.stringify(body),
                  {responseType: 'blob'})
              .then(({eCode, res, eMessage}) => {
                if (!eCode) {
                  let bytes = res;
                  let url = window.URL.createObjectURL(bytes);
                  commit('setAvatarUrl', {avatarUrl: url});
                  return;
                }
              });
        },
        logout({commit}) {
          commit("clear")
          router.push({path: '/login'});
        }
      }
}

